﻿using System;
using System.Linq;
using Coolite.Ext.Web;
using Pap.Data;
using Pap.Web.Modules.Loan.ViewModel;
using Pap.Web.Utils;
using Utils.UIPermission;

namespace Pap.Web.Modules.Loan.Views
{
    /// <summary>
    /// 
    /// </summary>
    public partial class LoanSocialResearchDetails : BaseUserControl<LoanSocialResearchDetailsViewModel>, IPermittedPage
    {
        #region QueryString Variables

        /// <summary>
        /// Gets the current loan ID.
        /// </summary>
        public string CurrentLoanID
        {
            get
            {
                return this.Request.QueryString["LoanID"];
            }
        }

        #endregion

        #region Event Handlers

        /// <summary>
        /// Handles the Load event of the Page control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!this.IsPostBack && !Ext.IsAjaxRequest)
            {
                FillCustomerInfo();
                FillSocialResearchInfo();
            }
        }



        /// <summary>
        /// Handles the Clicked event of the btnAccept control.
        /// </summary>
        /// <param name="sender">The source of the event.</param>
        /// <param name="args">The <see cref="Coolite.Ext.Web.AjaxEventArgs"/> instance containing the event data.</param>
        protected void btnAccept_Clicked(object sender, AjaxEventArgs args)
        {
            if (rdoAccept.Checked)
                AcceptSocialResearch();
            else if (rdoRefuse.Checked)
                RefuseSocialResearch();
            else if (rdoFreeze.Checked)
                FreezeSocialResearch();
        }


        #endregion

        #region Private Functions

        /// <summary>
        /// Fills the social research info.
        /// </summary>
        private void FillSocialResearchInfo()
        {
            this.dateFreeze.Hidden = true;
            this.rdoAccept.Checked = true;
            //-----------------------------------------------------------------------------------------
            ILoanSocialResearch currentResearch = this.ViewModel.GetSocialResearchForLoan(CurrentLoanID);
            if (currentResearch != null)
            {
                txtFamilyNumberSocial.Text = currentResearch.FamilyNumbers.ToString();
                txtTotalIncomeSocial.Text = currentResearch.IncomeAmount.ToString();
                txtNotesSocial.Text = currentResearch.Notes;

                insertAttachmentsSocial.SetImages(currentResearch.Attachements.Select(att => att.AttachmentImage));
            }

        }

        /// <summary>
        /// Fills the customer info.
        /// </summary>
        private void FillCustomerInfo()
        {
            ICustomer currentCustomer = this.ViewModel.GetCustomerFromLoan(CurrentLoanID);
            this.txtNameSocial.Text = currentCustomer.CustomerName;
            this.txtNationalIDSocial.Text = currentCustomer.SSN;
            insertAttachmentsSocial.ExtraLabel = String.Format("{0}, {1}, ", this.txtNameSocial.Text, this.ViewModel.GetLoan(CurrentLoanID).LoanNumber);
        }

        /// <summary>
        /// Freezes the social research.
        /// </summary>
        private void FreezeSocialResearch()
        {
            try
            {
                DateTime? CompletionDate = Convert.ToDateTime(dateFreeze.Value);

                var insertedAttachmentIds = this.insertAttachmentsSocial.GetInsertedIDs();
                var deletedAttachemnetsIds = this.insertAttachmentsSocial.GetDeletedIDs();
                insertAttachmentsSocial.Save();

                this.ViewModel.SaveSocialResearch(CurrentLoanID, insertedAttachmentIds, deletedAttachemnetsIds,
                    txtFamilyNumberSocial.Text.ToInt32(), double.Parse(txtTotalIncomeSocial.Text), txtNotesSocial.Text, Pap.Services.WorkflowEngine.ActionTypes.Freeze,
                    CompletionDate);

                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBFreeze").ToString(),
                    Message = GetLocalResourceObject("MSGFreeze").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();

            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MSGError").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
        }

        /// <summary>
        /// Accepts the social research.
        /// </summary>
        private void AcceptSocialResearch()
        {
            try
            {
                var insertedAttachmentIds = this.insertAttachmentsSocial.GetInsertedIDs();
                var deletedAttachemnetsIds = this.insertAttachmentsSocial.GetDeletedIDs();
                insertAttachmentsSocial.Save();

                this.ViewModel.SaveSocialResearch(CurrentLoanID, insertedAttachmentIds, deletedAttachemnetsIds,
                    txtFamilyNumberSocial.Text.ToInt32(), double.Parse(txtTotalIncomeSocial.Text), txtNotesSocial.Text, Pap.Services.WorkflowEngine.ActionTypes.Accept, null);

                var dlgt = (EventHandler)this.Events["OnAccept"];
                if (dlgt != null)
                    dlgt(this, EventArgs.Empty);

                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBAccepted").ToString(),
                    Message = GetLocalResourceObject("MSGAccepted").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MSGError").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
        }

        /// <summary>
        /// Refuses the social research.
        /// </summary>
        private void RefuseSocialResearch()
        {
            try
            {
                var insertedAttachmentIds = this.insertAttachmentsSocial.GetInsertedIDs();
                var deletedAttachemnetsIds = this.insertAttachmentsSocial.GetDeletedIDs();
                insertAttachmentsSocial.Save();

                this.ViewModel.SaveSocialResearch(CurrentLoanID, insertedAttachmentIds, deletedAttachemnetsIds,
                    txtFamilyNumberSocial.Text.ToInt32(), double.Parse(txtTotalIncomeSocial.Text), txtNotesSocial.Text, Pap.Services.WorkflowEngine.ActionTypes.Refuse, null);

                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.INFO,
                    Title = GetLocalResourceObject("MBRefused").ToString(),
                    Message = GetLocalResourceObject("MSGRefused").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
            catch
            {
                Ext.Msg.Configure(new MessageBox.Config
                {
                    Icon = MessageBox.Icon.ERROR,
                    Title = GetLocalResourceObject("MBError").ToString(),
                    Message = GetLocalResourceObject("MSGError").ToString(),
                    Buttons = MessageBox.Button.OK,
                }).Show();
            }
        }
        #endregion

        #region IPermittedPage Members

        /// <summary>
        /// Gets the name of the permission.
        /// </summary>
        /// <value>
        /// The name of the permission.
        /// </value>
        public string PermissionName
        {
            get { return "LoanSocialResearchDetails"; }
        }

        #endregion

        /// <summary>
        /// Occurs when [on accept].
        /// </summary>
        public event EventHandler Accept
        {
            add
            {
                this.Events.AddHandler("OnAccept", value);
            }
            remove
            {
                this.Events.RemoveHandler("OnAccept", value);
            }
        }
    }
}
